import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class PersonalVerificationScreen extends StatefulWidget {
  const PersonalVerificationScreen({super.key});

  @override
  State<PersonalVerificationScreen> createState() => _PersonalVerificationScreenState();
}

class _PersonalVerificationScreenState extends State<PersonalVerificationScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _idNumberController = TextEditingController();
  
  bool _isSubmitting = false;
  int _currentStep = 0;
  
  @override
  void dispose() {
    _nameController.dispose();
    _idNumberController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF333333)),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          '个人认证',
          style: TextStyle(
            color: Color(0xFF333333),
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
      ),
      body: Column(
        children: [
          // 进度指示器
          Container(
            color: Colors.white,
            padding: const EdgeInsets.symmetric(vertical: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildStepIndicator(0, '填写信息', _currentStep >= 0),
                Container(
                  width: 40,
                  height: 2,
                  color: _currentStep >= 1 ? const Color(0xFF1890FF) : const Color(0xFFE8E8E8),
                ),
                _buildStepIndicator(1, '上传证件', _currentStep >= 1),
                Container(
                  width: 40,
                  height: 2,
                  color: _currentStep >= 2 ? const Color(0xFF1890FF) : const Color(0xFFE8E8E8),
                ),
                _buildStepIndicator(2, '人脸识别', _currentStep >= 2),
              ],
            ),
          ),
          
          // 内容区域
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(20),
              child: _buildCurrentStepContent(),
            ),
          ),
          
          // 底部按钮
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(20),
            child: SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _isSubmitting ? null : _handleNextStep,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF1890FF),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  elevation: 0,
                ),
                child: _isSubmitting
                    ? const SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : Text(
                        _getButtonText(),
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStepIndicator(int step, String title, bool isActive) {
    return Column(
      children: [
        Container(
          width: 32,
          height: 32,
          decoration: BoxDecoration(
            color: isActive ? const Color(0xFF1890FF) : const Color(0xFFE8E8E8),
            shape: BoxShape.circle,
          ),
          child: Center(
            child: Text(
              '${step + 1}',
              style: TextStyle(
                color: isActive ? Colors.white : const Color(0xFF999999),
                fontSize: 14,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
        const SizedBox(height: 8),
        Text(
          title,
          style: TextStyle(
            fontSize: 12,
            color: isActive ? const Color(0xFF1890FF) : const Color(0xFF999999),
            fontWeight: isActive ? FontWeight.w600 : FontWeight.normal,
          ),
        ),
      ],
    );
  }

  Widget _buildCurrentStepContent() {
    switch (_currentStep) {
      case 0:
        return _buildPersonalInfoStep();
      case 1:
        return _buildDocumentUploadStep();
      case 2:
        return _buildFaceRecognitionStep();
      default:
        return _buildPersonalInfoStep();
    }
  }

  Widget _buildPersonalInfoStep() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 20,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '填写个人信息',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: Color(0xFF333333),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '请确保信息真实有效，提交后不可修改',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 24),
            
            // 姓名输入
            const Text(
              '真实姓名',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: Color(0xFF333333),
              ),
            ),
            const SizedBox(height: 8),
            TextFormField(
              controller: _nameController,
              decoration: InputDecoration(
                hintText: '请输入真实姓名',
                hintStyle: TextStyle(
                  color: Colors.grey[400],
                  fontSize: 14,
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: const BorderSide(color: Color(0xFFE8E8E8)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: const BorderSide(color: Color(0xFFE8E8E8)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: const BorderSide(color: Color(0xFF1890FF)),
                ),
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入真实姓名';
                }
                if (value.length < 2) {
                  return '姓名长度不能少于2个字符';
                }
                return null;
              },
            ),
            const SizedBox(height: 20),
            
            // 身份证号输入
            const Text(
              '身份证号码',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: Color(0xFF333333),
              ),
            ),
            const SizedBox(height: 8),
            TextFormField(
              controller: _idNumberController,
              keyboardType: TextInputType.text,
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp(r'[0-9Xx]')),
                LengthLimitingTextInputFormatter(18),
              ],
              decoration: InputDecoration(
                hintText: '请输入18位身份证号码',
                hintStyle: TextStyle(
                  color: Colors.grey[400],
                  fontSize: 14,
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: const BorderSide(color: Color(0xFFE8E8E8)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: const BorderSide(color: Color(0xFFE8E8E8)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: const BorderSide(color: Color(0xFF1890FF)),
                ),
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入身份证号码';
                }
                if (value.length != 18) {
                  return '请输入18位身份证号码';
                }
                return null;
              },
            ),
            const SizedBox(height: 24),
            
            // 温馨提示
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFFF6FFED),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: const Color(0xFFB7EB8F),
                  width: 1,
                ),
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Icon(
                    Icons.info_outline,
                    color: Color(0xFF52C41A),
                    size: 16,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '温馨提示',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: Color(0xFF52C41A),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '• 请确保姓名与身份证上的姓名完全一致\n• 身份证号码将用于实名验证，请仔细核对\n• 信息提交后不可修改，请谨慎填写',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[700],
                            height: 1.5,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDocumentUploadStep() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 20,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '上传身份证件',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '请上传清晰的身份证正反面照片',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 24),
          
          // 身份证正面
          _buildUploadCard(
            '身份证正面',
            '请确保证件信息清晰可见',
            Icons.credit_card,
            () => _uploadDocument('front'),
          ),
          const SizedBox(height: 16),
          
          // 身份证反面
          _buildUploadCard(
            '身份证反面',
            '请确保证件信息清晰可见',
            Icons.credit_card,
            () => _uploadDocument('back'),
          ),
          const SizedBox(height: 24),
          
          // 拍摄要求
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: const Color(0xFFFFF7E6),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(
                color: const Color(0xFFFFD591),
                width: 1,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Row(
                  children: [
                    Icon(
                      Icons.camera_alt,
                      color: Color(0xFFFAAD14),
                      size: 16,
                    ),
                    SizedBox(width: 8),
                    Text(
                      '拍摄要求',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFFFAAD14),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  '• 请在光线充足的环境下拍摄\n• 确保证件四角完整，信息清晰\n• 避免反光、模糊、遮挡\n• 支持JPG、PNG格式，大小不超过5MB',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[700],
                    height: 1.5,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUploadCard(String title, String subtitle, IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          border: Border.all(
            color: const Color(0xFFE8E8E8),
            width: 1,
          ),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          children: [
            Container(
              width: 60,
              height: 60,
              decoration: BoxDecoration(
                color: const Color(0xFFF0F2F5),
                borderRadius: BorderRadius.circular(30),
              ),
              child: Icon(
                icon,
                color: const Color(0xFF1890FF),
                size: 24,
              ),
            ),
            const SizedBox(height: 12),
            Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Color(0xFF333333),
              ),
            ),
            const SizedBox(height: 4),
            Text(
              subtitle,
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFaceRecognitionStep() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 20,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '人脸识别验证',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '请按照提示完成人脸识别验证',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 40),
          
          // 人脸识别图标
          Center(
            child: Container(
              width: 120,
              height: 120,
              decoration: BoxDecoration(
                color: const Color(0xFFF0F2F5),
                borderRadius: BorderRadius.circular(60),
              ),
              child: const Icon(
                Icons.face,
                color: Color(0xFF1890FF),
                size: 60,
              ),
            ),
          ),
          const SizedBox(height: 24),
          
          const Center(
            child: Text(
              '准备开始人脸识别',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Color(0xFF333333),
              ),
            ),
          ),
          const SizedBox(height: 40),
          
          // 验证要求
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: const Color(0xFFF6FFED),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(
                color: const Color(0xFFB7EB8F),
                width: 1,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Row(
                  children: [
                    Icon(
                      Icons.face_retouching_natural,
                      color: Color(0xFF52C41A),
                      size: 16,
                    ),
                    SizedBox(width: 8),
                    Text(
                      '验证要求',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF52C41A),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  '• 请在光线充足的环境下进行验证\n• 保持面部正对摄像头\n• 按照语音提示完成相应动作\n• 验证过程中请勿遮挡面部',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[700],
                    height: 1.5,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String _getButtonText() {
    switch (_currentStep) {
      case 0:
        return '下一步';
      case 1:
        return '下一步';
      case 2:
        return '开始验证';
      default:
        return '下一步';
    }
  }

  void _handleNextStep() {
    switch (_currentStep) {
      case 0:
        if (_formKey.currentState!.validate()) {
          setState(() {
            _currentStep = 1;
          });
        }
        break;
      case 1:
        setState(() {
          _currentStep = 2;
        });
        break;
      case 2:
        _startFaceRecognition();
        break;
    }
  }

  void _uploadDocument(String type) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('上传${type == 'front' ? '正面' : '反面'}照片'),
        content: const Text('请选择上传方式'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _showUploadSuccess(type);
            },
            child: const Text('拍照'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _showUploadSuccess(type);
            },
            child: const Text('相册'),
          ),
        ],
      ),
    );
  }

  void _showUploadSuccess(String type) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('${type == 'front' ? '正面' : '反面'}照片上传成功'),
        backgroundColor: const Color(0xFF52C41A),
      ),
    );
  }

  void _startFaceRecognition() {
    setState(() {
      _isSubmitting = true;
    });

    // 模拟人脸识别过程
    Future.delayed(const Duration(seconds: 3), () {
      setState(() {
        _isSubmitting = false;
      });
      
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => AlertDialog(
          title: const Text('认证提交成功'),
          content: const Text('您的个人认证信息已提交，我们将在1-3个工作日内完成审核。审核结果将通过短信和站内信通知您。'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context); // 关闭对话框
                Navigator.pop(context); // 返回上一页
              },
              child: const Text('确定'),
            ),
          ],
        ),
      );
    });
  }
}